/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dusin.teachassist.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.dusin.teachassist.util.CounterFile;

/**
 * Web application lifecycle listener.
 *
 * @author dusin
 */
@WebListener()
public class ContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext sc=sce.getServletContext();
        String dataDir = sc.getInitParameter("DataDirectory");
        if(dataDir==null||"".equals(dataDir)){
            dataDir="";
        }
        CounterFile countFileHandler=new CounterFile();//创建对象
        long count=countFileHandler.readFile(dataDir+"/count.txt");
        sce.getServletContext().setAttribute("count", count);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext sc=sce.getServletContext();
        String dataDir = sc.getInitParameter("DataDirectory");
        if(dataDir==null||"".equals(dataDir)){
            dataDir="";
        }
        CounterFile countFileHandler=new CounterFile();//创建对象
        long count = (Long)sce.getServletContext().getAttribute("count");
        countFileHandler.writeFile(dataDir+"/count.txt",count);//更新文件记录
    }
}
